package nl.boelen.game.server.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.TextArea;
import java.beans.Transient;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

import nl.boelen.game.gfx.Colors;
import nl.boelen.game.handler.WindowHandler;
import nl.boelen.game.net.packet.Packet13ClosedServer;
import nl.boelen.game.options.Option;
import nl.boelen.game.server.Server;
import nl.boelen.game.utils.Utils;

@SuppressWarnings("serial")
public class ServerGUI extends JFrame {
    private static final Dimension DIMENSION = new Dimension(Option.ServerWidth * Option.ServerScale, Option.ServerHeight * Option.ServerScale);

    private JTable playerTable;
    private JFrame frame;
    private TextArea console;

    public ServerGUI(final Server server) {
        frame = new JFrame(Option.GameName);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setResizable(false);
        frame.setVisible(true);

        frame.pack();
        frame.setPreferredSize(DIMENSION);
        frame.setMinimumSize(DIMENSION);
        frame.setMaximumSize(DIMENSION);

        WindowHandler windowHandler = new WindowHandler() {
            @Override
            public void windowClosed() {
                Packet13ClosedServer packet = new Packet13ClosedServer();
                server.players.sendTCPDataToAllClients(packet);
            }
        };

        frame.addWindowListener(windowHandler);

        // A simple table just to show all the client data (just for debugging)
        playerTable = new JTable(new TableModel(server.players, server.players.getConnectedPlayers()));

        console = new TextArea();
        console.setEditable(false);

        frame.add(new JScrollPane(playerTable), BorderLayout.NORTH);
        frame.add(console, BorderLayout.CENTER);
        frame.pack();
    }

    public void tick() {
        frame.repaint();
    }

    public void updateTable() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                playerTable.updateUI();
            }
        });
    }

    public void setGUITitle(String title) {
        frame.setTitle(title);
    }

    public void GUILog(String message) {
        console.append(Utils.getTime() + message + "\n");
    }
}
